package com.tlgen.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.tlgen.constant.Constant.READ_FILE_PATH;

public class FileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);

    public static final String UPLOAD_IMAGES_PATH = "E:\\uploadFile";

    public static final String IMAGE_BASE64 = "data:image/jpeg;base64,";

    private static SimpleDateFormat sdf = new SimpleDateFormat("/yyyyMMdd/");

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    public static String upload(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String format = sdf.format(new Date());
        String realPath = UPLOAD_IMAGES_PATH + format;
        String newName = "";
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        newName = UUID.randomUUID().toString().replaceAll("-", "")
                + filename.substring(filename.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String resultLocalPath = realPath.replaceAll("\\\\", "/").concat(newName);
        LOGGER.info("\n文件上传成功本地存储路径: " + resultLocalPath);
        return resultLocalPath;
    }

    /**
     * 获取指定文件夹下所有文件，不含文件夹里的文件
     *
     * @param dirFilePath 文件夹路径
     * @return
     */
    public static List<File> getAllFileAndDirectory(String dirFilePath) {
        List<File> resultFile = new ArrayList<File>();//新建一个文件集合
        File file = new File(dirFilePath);//File类型可以是文件也可以是文件夹
        if (file.exists()) {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isFile()) {//判断是否为文件
                    resultFile.add(fileList[i]);
                }
            }
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {//判断是否为文件夹
                    resultFile.add(fileList[i]);
                }
            }
        }
        return resultFile;
    }

    /**
     * 获取指定文件夹下所有文件，不含文件夹里的文件
     *
     * @param dirFilePath 文件夹路径
     * @return
     */
    public static List<File> getAllFile(String dirFilePath) {
        File file = new File(dirFilePath);//File类型可以是文件也可以是文件夹
        File[] fileList = file.listFiles();
        List<File> resultFile = new ArrayList<File>();//新建一个文件集合
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isFile()) {//判断是否为文件
                resultFile.add(fileList[i]);
            }
        }
        return resultFile;
    }

    /**
     * 获取指定文件夹下所有文件，不含文件夹里的文件
     *
     * @param dirFilePath 文件夹路径
     * @return
     */
    public static List<File> getAllEnvFile(String dirFilePath) {
        File file = new File(dirFilePath);//File类型可以是文件也可以是文件夹
        File[] fileList = file.listFiles();
        List<File> resultFile = new ArrayList<File>();//新建一个文件集合
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isFile()) {//判断是否为文件
                if (fileList[i].getName().contains(".env")) {
                    resultFile.add(fileList[i]);
                }
            }
        }
        return resultFile;
    }

    /**
     * 将 MultipartFile 转换为 File
     */
    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 读取文件内容
     *
     * @param file
     * @return
     */
    public static String readFile(File file) {
        String text = "";
        String encoding = "utf-8";
        try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
             BufferedReader bufferedReader = new BufferedReader(read)) {
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    text += lineTxt + "\n";
                }
            } else {
                throw new RuntimeException("找不到指定的文件!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;
    }

    /**
     * 根据文件夹路径实现文件夹的复制（复制文件夹中的所有文件）
     *
     * @param sourceFolderPath
     * @param targetFolderPath
     */
    public static void copyFolder(String sourceFolderPath, String targetFolderPath) {
        File sourceFolder = new File(sourceFolderPath);
        String[] sourceFilePathList = sourceFolder.list();
        File targetFolder = new File(targetFolderPath);
        //判断目标文件夹是否存在,没有则创建
        if (!targetFolder.exists()) {
            targetFolder.mkdirs();
        }
        try {
            for (String filePath : sourceFilePathList) {
                if (new File(sourceFolderPath + sourceFolder.separator + filePath).isDirectory()) {
                    copyFolder(sourceFolderPath + sourceFolder.separator + filePath, targetFolderPath + sourceFolder.separator + filePath);
                }
                if (new File(sourceFolderPath + sourceFolder.separator + filePath).isFile()) {
                    copyFile(sourceFolderPath + sourceFolder.separator + filePath, targetFolderPath + sourceFolder.separator + filePath);
                }
            }
        } catch (IOException e) {
            System.out.println("复制文件夹信息出错");
        }
    }

    /**
     * 复制文件
     *
     * @param sourceFilePath
     * @param targetFilePath
     * @throws IOException
     */
    public static void copyFile(String sourceFilePath, String targetFilePath) throws IOException {
        File sourceFile = new File(sourceFilePath);
        File targetFile = new File(targetFilePath);
        FileInputStream inputStream = new FileInputStream(sourceFile);
        FileOutputStream outputStream = new FileOutputStream(targetFile);
        byte[] buffer = new byte[4096];
        int length = 0;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        inputStream.close();
        outputStream.close();
    }

    /**
     * 创建文件并写入内容
     */
    public static void createFile(String content) {
        try {
            File file = new File(READ_FILE_PATH);
            // 清空文件内容,  new FileWriter(file) 即使没有文件也会创建一个虚拟的文件
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("");
            fileWriter.flush();
            fileWriter.close();
            // 写入内容
            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
            w.write(content);
            w.flush();
            w.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定目录下的全部文件
     *
     * @param path
     * @param fileList
     * @return
     */
    public static void getFiles(String path, List<File> fileList) {
        File file = new File(path);
        // 如果这个路径是文件夹
        if (file.isDirectory()) {
            // 获取路径下的所有文件
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                // 如果还是文件夹 递归获取里面的文件 文件夹
                if (files[i].isDirectory()) {
                    getFiles(files[i].getPath(), fileList);
                } else {
                    fileList.add(files[i]);
                }
            }
        } else {
            fileList.add(file);
        }
    }

}
